package handler

import (
	"context"
	"errors"
	. "rbac/models"
	pb "rbac/proto/rbacManager"
	"strconv"
	"time"
)

type RbacManager struct{}

// 获取角色
func (e *RbacManager) ManagerGet(ctx context.Context, req *pb.ManagerGetRequest, res *pb.ManagerGetResponse) error {
	var managerList []Manager
	where := "1=1"
	if req.Id > 0 {
		where += " AND id=" + strconv.Itoa(int(req.Id))
	}
	if len(req.Username) > 0 {
		where += " AND username=" + req.GetUsername()
	}
	DB.Preload("Role").Where(where).Find(&managerList)
	var tempList []*pb.ManagerModel
	for _, v := range managerList {
		tempList = append(tempList, &pb.ManagerModel{
			Id:       int64(v.ID),
			Username: v.Username,
			Password: v.Password,
			Mobile:   v.Mobile,
			Email:    v.Email,
			Status:   int64(v.Status),
			RoleId:   int64(v.RoleID),
			AddTime:  int64(v.AddTime),
			IsSuper:  int64(v.IsSuper),
			Role: &pb.RoleModel{
				Id:          int64(v.Role.ID),
				Title:       v.Role.Title,
				Description: v.Role.Description,
				Status:      int64(v.Role.Status),
				AddTime:     int64(v.Role.AddTime),
			},
		})
	}
	res.ManagerList = tempList
	return nil
}

// 增加角色
func (e *RbacManager) ManagerAdd(ctx context.Context, req *pb.ManagerAddRequest, res *pb.ManagerAddResponse) error {
	manager := Manager{
		Username: req.Username,
		Password: req.Password,
		Mobile:   req.Mobile,
		Email:    req.Email,
		Status:   int(req.Status),
		RoleID:   int(req.RoleId),
		AddTime:  int(time.Now().Unix()),
		IsSuper:  int(req.IsSuper),
	}
	if err := DB.Create(&manager).Error; err != nil {
		res.Success = false
		res.Message = "增加失败"
		return err
	}
	res.Success = true
	res.Message = "增加成功"
	return nil
}

// 编辑角色
func (e *RbacManager) ManagerEdit(ctx context.Context, req *pb.ManagerEditRequest, res *pb.ManagerEditResponse) error {
	var manager Manager
	DB.Where("id = ?", req.Id).Take(&manager)
	if manager.ID == 0 {
		res.Success = false
		res.Message = "角色不存在"
		return errors.New("角色不存在")
	}
	manager.Username = req.Username
	manager.Password = req.Password
	manager.Mobile = req.Mobile
	manager.Email = req.Email
	manager.Status = int(req.Status)
	manager.RoleID = int(req.RoleId)
	manager.IsSuper = int(req.IsSuper)
	if err := DB.Save(&manager).Error; err != nil {
		res.Success = false
		res.Message = "修改角色失败"
		return errors.New("修改角色失败")
	}
	res.Success = true
	res.Message = "修改角色成功"
	return nil
}

// 删除角色
func (e *RbacManager) ManagerDelete(ctx context.Context, req *pb.ManagerDeleteRequest, res *pb.ManagerDeleteResponse) error {
	var manager Manager
	DB.Where("id = ?", req.Id).Take(&manager)
	if manager.ID == 0 {
		res.Success = false
		res.Message = "角色不存在"
		return errors.New("角色不存在")
	}
	if err := DB.Delete(&manager).Error; err != nil {
		res.Success = false
		res.Message = "删除失败"
		return errors.New("删除失败")
	}
	res.Success = true
	res.Message = "删除成功"
	return nil
}
